package com.techfansy.photo;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.techfansy.moreImageSelected.ImagePicker;
import com.techfansy.moreImageSelected.MoreImageMethod;
import com.techfansy.moreImageSelected.bean.ImageItem;
import com.techfansy.provinceCitySelect.utils.Field;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 裁剪图片
 */
public class ImageCropActivity extends AppCompatActivity implements OnClickListener {
    private CCropImageView mCropImageView;
    private TextView mPick;
    private TextView mCancel;
    private Bitmap bitmap;
    private final static String path = Environment.getExternalStorageDirectory().getPath() + File.separator
            + "photo.jpg";
    public final static int REQUEST_ALBUM = 0X0016;
    private MoreImageMethod moreImageMethod;

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    private ImagePicker imagePicker;
    private List<ImageItem> mList = new ArrayList<>();
    private Uri uri;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        UIUtils.init(getApplicationContext());
        setContentView(this.getResources().getIdentifier("activity_crop_image", "layout", this.getPackageName()));
//        setOccupyViewColor(Color.parseColor("#000000"));

        mCropImageView = (CCropImageView) findViewById(new Field().getViewId(this, "crop_image"));
        mPick = (TextView) findViewById(new Field().getViewId(this, "crop_image_pick"));
        mCancel = (TextView) findViewById(new Field().getViewId(this, "crop_image_cancel"));
        mPick.setOnClickListener(this);
        mCancel.setOnClickListener(this);
        imagePicker = ImagePicker.getInstance();
        imagePicker.clear();
        moreImageMethod = new MoreImageMethod();
        if (getIntent().getBooleanExtra("isPicture", false)) {
            showAlbum();
        } else {
            if (Build.VERSION.SDK_INT >= 23) {
                int checkCallPhonePermission = ContextCompat.checkSelfPermission(ImageCropActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {

                    ActivityCompat.requestPermissions(ImageCropActivity.this, PERMISSIONS_STORAGE, 222);
                    return;
                } else {
                    openCamra();
                }
            } else {
                openCamra();//调用具体方法
            }
        }
    }

    private void openCamra() {
        moreImageMethod.setPhoto(this, imagePicker);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            //就像onActivityResult一样这个地方就是判断你是从哪来的。
            case 222:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamra();//调用具体方法
                } else {
                    // Permission Denied
                    Toast.makeText(ImageCropActivity.this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            case 333:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamra();//调用具体方法
                } else {
                    // Permission Denied
                    Toast.makeText(ImageCropActivity.this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    //从相册中上传头像
    private void showAlbum() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, REQUEST_ALBUM);
    }

    private Bitmap getBitmapFromIntent(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            finish();
            return;
        }

        switch (requestCode) {
            /**
             * 拍照
             */
            case ImagePicker.REQUEST_CODE_TAKE:
                mList = moreImageMethod.onActivityResult(requestCode, resultCode, data, imagePicker, mList, this);
                Intent intent = getIntent();
                boolean isCrop = intent.getBooleanExtra("isCrop", false);
                if (isCrop) {
                    mCropImageView.setDrawable(new BitmapDrawable(getResources(), BitmapFactory.decodeFile(mList.get(0).getPaths())),
                            UIUtils.dip2px(this, 110), UIUtils.dip2px(this, 110));
                } else {

                    setIntentResult(mList.get(0).getPaths());
                }

                break;
            /**
             * 图册选择
             */
            case REQUEST_ALBUM:
                if (getIntent().getBooleanExtra("isCrop", false)) {
                    bitmap = getBitmapFromIntent(data.getData());
                    if (bitmap != null) {

                        mCropImageView.setDrawable(new BitmapDrawable(getResources(), bitmap),
                                UIUtils.dip2px(this, 110), UIUtils.dip2px(this, 110));
                    }
                } else {

                    setIntentResult(data.getData().getPath());
                }

                break;
        }
    }

    private String getFilePathByContentResolver(Context context, Uri uri) {
        if (null == uri) {
            return null;
        }
        Cursor c = context.getContentResolver().query(uri, null, null, null, null);
        String filePath = null;
        if (null == c) {
            throw new IllegalArgumentException(
                    "Query on " + uri + " returns null result.");
        }
        try {
            if ((c.getCount() != 1) || !c.moveToFirst()) {
            } else {
                filePath = c.getString(
                        c.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA));
            }
        } finally {
            c.close();
        }
        return filePath;
    }

    public void setIntentResult(String path) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        if (!TextUtils.isEmpty(path))
            bundle.putString("path", path);
        intent.putExtras(bundle);
        setResult(PhotoSelect.REQUEST_CAMERA, intent);
        finish();
    }

    @Override
    public void onClick(View v) {
        if (v == mPick) {
            if (mCropImageView.getWidth() > 0 && mCropImageView.getHeight() > 0) {
                //成功加载了图片
                Bitmap bitmap = mCropImageView.getCropImage();
                setIntentResult(saveBitmapFile(bitmap));
            }
        } else {
            onBackPressed();
        }
//

    }

    //Bitmap对象保存味图片文件
    public String saveBitmapFile(Bitmap bitmap) {
        String url = null;
        File file = new File(path);//将要保存图片的路径
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            url = path;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    //图片过大导致内存溢出，在退出当前Activity的时候释放资源
    @Override
    protected void onDestroy() {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
        super.onDestroy();
    }


    public static int getIdByName(Context context, String className, String name) {
        String packageName = context.getPackageName();
        Class r = null;
        int id = 0;
        try {
            r = Class.forName(packageName + ".R");

            Class[] classes = r.getClasses();
            Class desireClass = null;

            for (int i = 0; i < classes.length; ++i) {
                if (classes[i].getName().split("\\$")[1].equals(className)) {
                    desireClass = classes[i];
                    break;
                }
            }

            if (desireClass != null)
                id = desireClass.getField(name).getInt(desireClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        return id;

    }


}
